var common = requireMod("common");
var dsAppId = getSysConfig("dsAppId");

/**
 * 获取ip地址
 * @param  {Object} req http请求信息
 * @return {String}     ip地址
 */
function getIP(headers) {
    var ip = "";
    if(headers["x-forwarded-for"]){
        ip = headers["x-forwarded-for"];
    }else if(headers["x-real-ip"]){
        ip = headers["x-real-ip"];
    }else if(headers["remote_addr"] && headers["client_ip"]){
        ip = headers["client_ip"];
    }else if(headers["remote_addr"]){
        ip =headers["remote_addr"];
    }else if(headers["client_ip"]){
        ip =headers["client_ip"];
    }else {
        return "0.0.0.0";
    }
    ip = ip && ip.split(",")[0] || "0.0.0.0";

    return ip;
};

function getDef(headers){
    return {
        "taskId":dsAppId
        ,"ip":getIP(headers)
        ,"timestampId":Date.now()
        ,"date":common.date("Y-m-d h:i:s",new Date())
    }
}

function getLogData(headers, query){
    return Object.assign(
        getDef(headers)
        ,query || {}
    );
}


module.exports = async function (ctx, next) {
    if (ctx.url.indexOf("collect") !== -1) {
        var dat = getLogData(ctx.headers, ctx.query);
        if (dat.log_type === "pageview") {
            dat.fromDsId = null;
            dat.fromTimestamp = null;
        }
        ctx.state.collect = dat;
    }

    await next();
}
